import React, { useEffect, useState } from 'react'
import Video from "react-native-video";
import { View, Text, TouchableOpacity, Slider, Image, StyleSheet, Modal, ImageBackground, ScrollView, BackHandler } from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import Icon from 'react-native-vector-icons/AntDesign';
import { TextInput } from 'react-native-gesture-handler';
import { AsyncStorage } from 'react-native';
import {
    useFocusEffect,
} from '@react-navigation/native';

//定制好的分类歌单
let asleep = [
    {
        name: '星茶会',
        kind: '雨声|宁静|脚步',
        id: 1,
        source: require('../../Audio/1.mp3'),
    },
    {
        name: '萤之森',
        kind: '战争|宏大|脚步',
        id: 2,
        source: require('../../Audio/2.mp3'),
    },
    {
        name: '夏日之梦',
        kind: '..|Happy|脚步',
        id: 3,
        source: require('../../Audio/3.mp3'),
    },
    {
        name: '轻风',
        kind: '..|Happy|脚步',
        id: 4,
        source: require('../../Audio/4.mp3'),
    },
    {
        name: '夏に花が散る',
        kind: '..|Happy|脚步',
        id: 5,
        source: require('../../Audio/5.mp3'),
    }
]
let read = [
    {
        name: '莲有秀兮',
        kind: '雨声|宁静|脚步',
        id: 6,
        source: require('../../Audio/6.mp3'),
    },
    {
        name: 'Rain after Summe',
        kind: '雨声|宁静|脚步',
        id: 7,
        source: require('../../Audio/7.mp3'),
    },
    {
        name: 'Natures Path (自然小径)',
        kind: '雨声|宁静|脚步',
        id: 8,
        source: require('../../Audio/8.mp3'),
    },
    {
        name: 'Gypsophila',
        kind: '雨声|宁静|脚步',
        id: 9,
        source: require('../../Audio/9.mp3'),
    },

    {
        name: 'Jsan - pure imagination',
        kind: '雨声|宁静|脚步',
        id: 10,
        source: require('../../Audio/10.mp3'),
    }

]
let sleep = [
    {
        name: '拿花负荷',
        kind: '雨声|宁静|脚步',
        id: 11,
        source: require('../../Audio/11.mp3'),
    },
    {
        name: ' Love Is Gone (钢琴版)',
        kind: '雨声|宁静|脚步',
        id: 12,
        source: require('../../Audio/12.mp3'),
    },
    {
        name: '我去偷星星，夜里等你♡',
        kind: '雨声|宁静|脚步',
        id: 13,
        source: require('../../Audio/13.mp3'),
    },
    {
        name: 'The Way I Still Love You (治愈版)',
        kind: '雨声|宁静|脚步',
        id: 14,
        source: require('../../Audio/14.mp3'),
    },
    {
        name: 'The Way I Still Love You (纯音乐)',
        kind: '雨声|宁静|脚步',
        id: 15,
        source: require('../../Audio/15.mp3'),
    }
]
let sport = [
    {
        name: '盐甜汽水',
        kind: '解压|宁静|运动',
        id: 16,
        source: require('../../Audio/16.mp3'),
    },
    {
        name: '长风游',
        kind: '解压|宁静|运动',
        id: 17,
        source: require('../../Audio/17.mp3'),
    },
    {
        name: '柠檬街',
        kind: '解压|宁静|运动',
        id: 18,
        source: require('../../Audio/18.mp3'),
    },
    {
        name: '纸飞机',
        kind: '解压|宁静|运动',
        id: 19,
        source: require('../../Audio/19.mp3'),
    },
    {
        name: '辞阁去',
        kind: '解压|宁静|运动',
        id: 20,
        source: require('../../Audio/20.mp3'),
    },
]
let walk = [
    {
        name: '秒 · 星烁',
        kind: '解压|散步|轻松',
        id: 21,
        source: require('../../Audio/21.mp3'),
    },
    {
        name: '木鲸',
        kind: '解压|散步|轻松',
        id: 22,
        source: require('../../Audio/22.mp3'),
    },
    {
        name: '8月31日',
        kind: '解压|散步|轻松',
        id: 23,
        source: require('../../Audio/23.mp3'),
    },
    {
        name: '撒野',
        kind: '解压|散步|轻松',
        id: 24,
        source: require('../../Audio/24.mp3'),
    },
    {
        name: '青空',
        kind: '解压|散步|轻松',
        id: 25,
        source: require('../../Audio/25.mp3'),
    },
]

const Test = ({ navigation, route }) => {
    useFocusEffect(
        React.useCallback(() => {
            return () => {
                navigation.navigate('list');
            };
        }, [])
    );

    //用户名字
    const [pName,setName] = useState('');
    const getName = async () => {
        let data = await AsyncStorage.getItem('name');
        data = JSON.parse(data);
        return data;
    }
    useEffect(async()=>{
        await getName().then((res)=>{
            setName(res);
        });
    },[])
    //歌曲数组
    const [songList, setSongList] = useState(walk);
    //针对不同的歌单进行当前歌曲数组赋值
    if (route.params.text != undefined) {
        //拿到分类歌单的具体分类
        let text = route.params.text;
        useEffect(() => {
            switch (text) {
                case '散步':
                    setSongList([...walk]);
                    break;
                case '运动':
                    setSongList([...sport]);
                    break;
                case '午睡':
                    setSongList([...asleep]);
                    break;
                case '看书':
                    setSongList([...read]);
                    break;
                case '安眠':
                    setSongList([...sleep]);
                    break;
            }
        }, [text])
    }
    //那到听友推荐的歌曲
    if (route.params.id != undefined) {
        let songId = route.params.id;
        useEffect(() => {
            if (songId >= 21) {
                songId = songId - 20 - 1;
                setSongList([walk[songId]]);
            }
            else if (songId >= 16) {
                songId = songId - 15 - 1;
                setSongList([walk[songId]]);
            }
            else if(songId >= 11){
                songId = songId - 10 - 1;
                setSongList([sleep[songId]]);
            }
            else if(songId >= 6){
                songId = songId - 5 - 1;
                setSongList([sport[songId]]);
            }
            else if(songId >= 1){
                songId = songId - 1;
                setSongList([walk[songId]])
            }
              
        }, [songId])
    }


    //收藏数组功能和方法的实现
    const getData = async () => {
        console.log('获取数据');
        let data = await AsyncStorage.getItem('soucang');
        data = JSON.parse(data);
        if (data == null) {
            data = [];
            return data;
        } else {
            return data;
        }
    }
    const saveData = async (data) => {
        console.log('存储');
        console.log(data);
        data = JSON.stringify(data);
        await AsyncStorage.setItem(
            'soucang',data
        );
    }
    let [soucang, setSouCang] = useState([]);
    useEffect(() => {
        getData().then((res) => {
            let data = res;
            setSouCang([...data]);
        });
    },[])


    //1.下端功能栏目
    //设置是否弹出
    const [modalVisible, setModalVisible] = useState([false, false, false]);

    //定时器
    //定时关闭的配置
    const timeList = [
        {
            title: '不开启',
            time: 0
        },
        {
            title: '5分钟',
            time: 0.1
        },
        {
            title: '25分钟',
            time: 25
        },
        {
            title: '45分钟',
            time: 45
        },
        {
            title: '60分钟',
            time: 60
        }

    ]
    const [clockList, setClockList] = useState([true, false, false, false, false]);
    //定时关闭功能定时器
    let timer1 = '';
    const [timer, setTimer] = useState(0);
    useEffect(() => {
        timer1 = setTimeout(() => {
            if (timer >= 1) {
                setTimer((timer) => --timer);
            } else {
                //执行停止播放操作
                changeState(0);
                setIconName('play');
                //改变定时的选中状态
                setClockList([true, false, false, false, false]);
            }
        }, 1000);
    }, [timer]);

    //评论歌曲的文字
    const [value, onChangeText] = useState('');
    //获得提交的文字以及歌曲等信息
    const saveRecord = async (author,content,id) => {
        // AsyncStorage.removeItem('record');
        
        //获得原来存储的内容
        let oldData = await AsyncStorage.getItem('record');
        oldData = JSON.parse(oldData);
        if(oldData==null){
            oldData = [
                { author: '林季子', content: '在一个孤岛上，有只小猫猫陪在你的身旁。', id: 2 },
                { author: 'weijoyer', content: '家里老旧的挂表，与取暖的火炉，下着小雨', id: 6 },
                { author: '温柔', content: '在丛林里坐在篝火旁听着虫鸣，风声进入梦乡。', id: 9 },
                { author: '林深见鹿', content: '超级放松的感觉！很轻松！', id: 10 },
            ];
        }
        let data = {
            author,
            content,
            id
        }
        oldData.unshift(data);
        oldData = JSON.stringify(oldData);
        await AsyncStorage.setItem(
            'record',oldData
        );
    }

    

    //收藏功能
    const [record, setRecord] = useState('hearto');

    //2.歌曲
    //获取数组的长度
    let listLength = songList.length;
    //当前歌曲的位置
    const [songIndex, setSongIndex] = useState(0);
    //播放和暂停
    const [state, changeState] = useState(0);
    //歌曲的总时长
    const [time, setTime] = useState('');
    //歌曲的播放进度
    const [nowtime, setNowTime] = useState('00:00');
    //歌曲播放图标的设置
    const [iconName, setIconName] = useState('play');




    //主播放界面涉及到的方法
    //暂停播放的方法
    const changeVideo = () => {
        if (state == 0) {
            changeState(1);
            setIconName('pausecircle');
        } else {
            changeState(0);
            setIconName('play');
        }
    }
    //得到歌曲时间
    const getSingTime = (data) => {
        let singtime = data.duration;
        setTime(formatTime(singtime));
    }

    //得到当前播放事件
    const getNowTime = (data) => {
        setNowTime(formatTime(data.currentTime));
    }

    //格式化歌曲时间
    const formatTime = (time) => {
        //判断传入的是否为0 为0直接不显示
        if (time == 0) {
            return '';
        }
        //数组转字符串
        time = time + '';
        let index = time.indexOf('.');
        //进行去除小数点的工作
        if (index != -1) {
            time = time.slice(0, index);
            time = Number(time);
        }
        //实现格式
        let min = Math.floor(time / 60); //分钟数
        let second = time - min * 60; //秒数
        min = min >= 10 ? min : "0" + min;
        second = second >= 10 ? second : "0" + second;
        return min + ":" + second;
    }

    //检查收藏歌单中是否存在本首歌
    const isLike = () => {
        let end = soucang.some((item) => {
            return item.id == songList[songIndex].id
        })
        if (end == true) {
            setRecord('heart');
        } else {
            setRecord('hearto');
        }
    }

    //播放上一首歌
    const playLastSong = () => {
        if (songIndex == 0) {
            return;
        } else {
            let newIndex = songIndex;
            setSongIndex(--newIndex);
            changeState(1);
            setIconName('pausecircle');
            isLike();
        }
    }

    //播放下一首歌
    const playNextSong = () => {
        if (songIndex == (listLength - 1)) {
            return;
        } else {
            let newIndex = songIndex;
            setSongIndex(++newIndex);
            //直接开始播放 图标改变
            changeState(1);
            setIconName('pausecircle');
            isLike();
        }
    }

    //歌曲播放完执行的行为
    const finishAction = () => {
        setNowTime(time);
        if (songIndex == (listLength - 1)) {
            return;
        } else {
            let newIndex = songIndex;
            setSongIndex(++newIndex);
            //直接开始播放 图标改变
            changeState(1);
            setIconName('pausecircle');
        }

    }
    //初始检查本首歌是否收藏
    useEffect(() => {
        isLike();
    })

    //监听回退事件
    // const backAction = () => {
    //     saveData([...soucang])
    //     navigation.navigate('list',{id:songList[songIndex].id})
    //     return true;
    // };
    // useEffect(() => {
    //     BackHandler.addEventListener("hardwareBackPress", backAction);
    // });

    return (
        <View>
            {/* 播放器的控制项目 */}
            <Video source={songList[songIndex].source}
                rate={state}
                playInBackground={true} //切到后台也可以播放
                onLoad={data => getSingTime(data)} //获取歌曲的总长度
                onProgress={e => {
                    if (state == 1) {
                        getNowTime(e);
                    }
                }} //获取歌曲的当前长度

                onEnd={() => finishAction()}
            />

            {/* 功能弹出区 */}
            {/* 定时器模块 */}
            <Modal
                animationType="slide"
                transparent={true}
                visible={modalVisible[0]}
                onRequestClose={() => {
                    setModalVisible([false, false, false]);
                }}
            >
                <View style={styles.centeredView}>
                    <View style={{ display: 'flex', width: w, height: h / 2, paddingLeft: 30, paddingRight: 30 }}>
                        <View style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', flex: 1, backgroundColor: 'white', borderRadius: 10, paddingLeft: 20, paddingRight: 20 }}>
                            <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                <Text style={{ fontSize: 20, fontWeight: 'bold', marginTop: 6 }}>定时关闭</Text>
                            </View>
                            {
                                timeList.map((item, key) => {
                                    return (
                                        <TouchableOpacity key={key} style={styles.modelSonItem} onPress={
                                            () => {
                                                let newTimeList = [false, false, false, false, false];
                                                newTimeList[key] = true;
                                                setClockList(newTimeList);
                                                clearTimeout(timer1);
                                                setTimer(() => timeList[key].time * 60);
                                            }
                                        }>
                                            <Text>{item.title}</Text>
                                            {
                                                clockList.map((item, index) => {
                                                    if (item == true && key == index) {
                                                        return (
                                                            <Icon name="check" size={20} key={index}></Icon>
                                                        )
                                                    }
                                                })
                                            }
                                        </TouchableOpacity>

                                    )
                                })
                            }
                        </View>
                    </View>
                </View>
            </Modal>

            {/* 评论模块 */}
            <Modal
                animationType="slide"
                transparent={true}
                visible={modalVisible[1]}
                onRequestClose={() => {
                    setModalVisible([false, false, false]);
                }}
            >
                <View style={{ display: 'flex', flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                    <View style={{ display: 'flex', width: w * 2 / 3, height: w * 1 / 3, backgroundColor: 'white', flexDirection: 'column', justifyContent: 'flex-end', borderRadius: 10 }}>
                        <TextInput style={{ flex: 4 }} placeholder='说点什么吧' multiline={true} numberOfLines={4}
                            onChangeText={text => onChangeText(text)}
                            value={value}
                        ></TextInput>

                        <TouchableOpacity style={{ flex: 1.5, display: 'flex', flexDirection: 'row', justifyContent: 'flex-end' }}
                            onPress={()=>{
                                saveRecord(pName,value,songList[songIndex].id);
                                setModalVisible([false,false,false]);
                            }}>
                            <View style={{ backgroundColor: 'red', marginBottom: 5, marginRight: 5, borderRadius: 5 }}>
                                <Text style={{ color: 'white', fontSize: 14, height: 18, margin: 5 }}>发布</Text>
                            </View>

                        </TouchableOpacity>
                    </View>
                </View>

            </Modal>

            {/* 收藏列表区 */}
            <Modal
                animationType="slide"
                transparent={true}
                visible={modalVisible[2]}
                onRequestClose={() => {
                    setModalVisible([false, false, false]);
                }}
            >
                <View style={{ display: 'flex', flex: 1, alignItems: 'center', justifyContent: 'flex-end' }}>
                    <View style={{ display: 'flex', width: w * 6 / 7, height: h * 2 / 3, backgroundColor: 'white', flexDirection: 'column', borderRadius: 10, marginBottom: 30, paddingRight: 10, paddingLeft: 10, paddingTop: 10 }}>
                        <Text style={{ fontSize: 26, fontWeight: 'bold', marginBottom: 10 }}>我喜欢的</Text>
                        <ScrollView style={{ flex: 1 }}>
                            {
                                soucang.map((item, key) => {
                                    return (
                                        <TouchableOpacity style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', marginBottom: 10 }} key={key} onPress={
                                            () => {
                                                //完成当前音乐数组的切换
                                                setSongList([...soucang]);
                                                setSongIndex(--key);
                                                setModalVisible([false,false,false]);
                                            }
                                        }>
                                            <Text style={{ flex: 1, textAlign: 'center', color: '#AEAEAE' }}>{++key}</Text>
                                            <View style={{ display: 'flex', flexDirection: 'column', flex: 9 }}>
                                                <Text style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 5 }}>{item.name}</Text>
                                                <View style={{ display: 'flex', flexDirection: 'row' }}>
                                                    {
                                                        item.kind.split('|').map((item, key) => {
                                                            return (
                                                                <View style={{ backgroundColor: '#F5F6FB', padding: 5, borderRadius: 5, marginRight: 10 }} key={key}>
                                                                    <Text style={{ color: '#B3B4B9' }}>{item}</Text>
                                                                </View>

                                                            )

                                                        })
                                                    }
                                                </View>
                                            </View>
                                        </TouchableOpacity>
                                    )
                                })
                            }
                        </ScrollView>
                    </View>
                </View>

            </Modal>


            {/* 界面区域 */}
            <LinearGradient
                colors=
                {[
                    '#AFAFB9',
                    '#CCCBD1',
                    '#E6E6E8',]
                }
            >
                <View style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', position: 'relative' }}>

                    {/* 歌曲封面的图标 */}
                    <Image source={require('../../Image/pic.jpg')} style={styles.pic}></Image>

                    {/* 显示歌曲播放进度 */}
                    <Text style={{ marginTop: pth(15), fontSize: 18, color: '#B2B2BC' }}>{nowtime}----{time}</Text>

                    {/* 显示歌名 */}
                    <Text style={{ fontWeight: 'bold', fontSize: 34, marginTop: pth(7) }}>{songList[songIndex].name}</Text>

                    {/* 显示标签 */}
                    <Text style={{ fontSize: 23, marginTop: pth(6), color: '#B9BABF' }}>{songList[songIndex].kind}</Text>

                    {/* 播放等按钮 */}
                    <View style={{ width: ptd(300), marginTop: pth(12), display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around' }}>
                        {/* 上一首歌 */}
                        <TouchableOpacity onPress={() => playLastSong()}>
                            <Icon name='stepbackward' size={40} color='black'></Icon>
                        </TouchableOpacity>

                        {/* 播放与暂停 */}
                        <TouchableOpacity onPress={() => changeVideo()}>
                            <Icon name={iconName} size={60} color='black'></Icon>
                        </TouchableOpacity>

                        {/* 下一首歌 */}
                        <TouchableOpacity onPress={() => playNextSong()}>
                            <Icon name='stepforward' size={40} color='black'></Icon>
                        </TouchableOpacity>
                    </View>

                    {/* 底部工具栏按钮 */}
                    <View style={{ width: w, display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', position: 'absolute', bottom: 14 }}>
                        <TouchableOpacity onPress={() => {
                            setModalVisible([true, false, false]);
                        }}>
                            <Icon name='clockcircleo' size={28}></Icon>
                            <Text>{timer == 0 ? '' : formatTime(timer)}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity onPress={() => {
                            setModalVisible([false, true, false]);
                        }}>
                            <Icon name='message1' size={28}></Icon>
                            <Text></Text>
                        </TouchableOpacity>

                        <TouchableOpacity onPress={() => {
                            if (record == 'hearto') {
                                setSouCang((soucang) => [{
                                    name: songList[songIndex].name,
                                    kind: songList[songIndex].kind,
                                    id: songList[songIndex].id,
                                    source: songList[songIndex].source
                                }, ...soucang])
                                setRecord('heart');
            

                            } else {
                                setSouCang((soucang) => soucang = soucang.filter(
                                    function (item) {
                                        return item.id != songList[songIndex].id;
                                    }
                                ))
                               
                                setRecord('hearto');
                            }

                        }}>
                            <Icon name={record} size={28} style={record == 'heart' ? { color: 'red' } : { color: 'black' }}></Icon>
                            <Text></Text>
                        </TouchableOpacity>

                        <TouchableOpacity onPress={() => {
                            setModalVisible([false, false, true]);
                        }}>
                            <Icon name='bars' size={28}></Icon>
                            <Text></Text>
                        </TouchableOpacity>



                    </View>

                </View>

            </LinearGradient>



        </View>

    )
}

const styles = StyleSheet.create({
    pic: {
        marginTop: pth(30),
        width: ptd(300),
        height: ptd(300),
        borderRadius: 28
    },
    centeredView: {
        display: 'flex',
        flex: 1,
        alignItems: 'center',
        justifyContent: 'flex-end',
        paddingBottom: 30
    },
    modelSonItem: {
        display: 'flex',
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    }
})

export default Test

